package com.uci.scheduleshare.adapters;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

import android.R.integer;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.format.DateFormat;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.uci.scheduleshare.CalendarView;
import com.uci.scheduleshare.R;
import com.uci.scheduleshare.calendar.Contact;
import com.uci.scheduleshare.calendar.Event;
import com.uci.scheduleshare.calendardb.CalendarDatabase;

/**
 * CS 190 Spring 2012
 * ViewPagerAdapter.java
 * The Adapter for displaying the main content - the calendar,
 * the contacts list, and the recent activities list. The PagerAdapter enables 
 * sliding pages.
 * 
 * @author Patrick Hsu, Lauren Ko, Pomi Park
 *
 */
public class ViewPagerAdapter extends PagerAdapter implements OnItemClickListener {
	
	private static final int CALENDAR_POS = 0;
	private static final int CONTACTS_POS = 1;
	private static final int ACTIVITYLOG_POS = 2;
	private String[] titles = new String[] { "My Calendar", "Contacts", "Recent Activity" };
	private final Context context;
	
	private CalendarDatabase db;
	private ContactsAdapter contactsAdapter;
	private RecentActivityAdapter activityAdapter;
	
	List<Contact> contacts;
	List<String> activities;
	private ListView contactsList;
	private ListView activitiesList;

	private final int calendarViewBackground = 0xFFdcdcdc;
	private final int textColor = 0xFF3c3c3c;
	
	private String[] days = new String[]{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
	private String[] times = new String[]{"12am", "1am", "2am", "3am", "4am", "5am", "6am",
			"7am", "8am", "9am", "10am", "11am", "12pm", "1pm", "2pm", "3pm", "4pm",
			"5pm", "6pm", "7pm", "8pm", "9pm", "10pm", "11pm"};
	
	/**
	 * Constructor - takes in all the objects created in the ScheduleShareActivity
	 */
	public ViewPagerAdapter(Context context, List<Contact> contacts, List<String> activities, 
				ContactsAdapter contactsAdapter, RecentActivityAdapter activityAdapter, CalendarDatabase db) {
		this.context = context;
		this.contactsAdapter = contactsAdapter;
		this.contacts = contacts;
		this.db = db;
		this.activityAdapter = activityAdapter;
		this.activities = activities;
	}
	
	/**
	 * Returns the page title of the current position
	 */
	@Override
	public CharSequence getPageTitle(int position) {
		return titles[position];
	}

	/**
	 * Returns the number of pages
	 */
	@Override
	public int getCount() {
		return titles.length;
	}

	/**
	 * Instantiates the view at the current position
	 */
	@Override
	public Object instantiateItem(View pager, int position) {
		LayoutInflater inflater = LayoutInflater
				.from(context);
		View layout = null;
		switch(position) {
		case CALENDAR_POS: { // If the user is at the calendar position, inflate calendar 
			layout = inflater.inflate(R.layout.calendar, null);
			
	        // Week label textview
	        TextView weekLabel = (TextView) layout.findViewById(R.id.weeklabel);
	        Calendar now = Calendar.getInstance();
	        now.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
	        Date todaysDate = now.getTime();
	        SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy");
	        String dateString = sdf.format(todaysDate);
	        weekLabel.setText("Week of "  + dateString);
			
			//instantiate calendarGrid
			//inflate days row
	        TableRow tr = (TableRow) layout.findViewById(R.id.days);
	        for (int i = 0; i < days.length; i++){
	        	TextView textView = new TextView(this.context);
	        	textView.setText(days[i]);
	        	textView.setTextColor(textColor);
	        	tr.addView(textView);
	        }
	        

	        //convert 50dp to px
	        float dip = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, context.getResources().getDisplayMetrics());
	        
	        // inflate times column
	        TableLayout tl = (TableLayout) layout.findViewById(R.id.times);
	        tl.setBackgroundColor(calendarViewBackground);
	        for (int i = 0; i < times.length; i++){
	        	TextView textView = new TextView(this.context);
	        	textView.setText(times[i]);
	        	textView.setMinimumHeight((int) dip);
	        	textView.setTextColor(textColor);
	        	tl.addView(textView);
	        }
	        
	        //inflate canvas
	        LinearLayout calendarLayout = (LinearLayout) layout.findViewById(R.id.calendarlayoutinner);
	        Random rng = new Random();  	
        	CalendarView calendarView = new CalendarView(this.context, contacts);
        	//calendarView.setBackgroundColor(Color.argb(rng.nextInt(256), rng.nextInt(256), rng.nextInt(256), rng.nextInt(256))); 
        	calendarView.setBackgroundColor(calendarViewBackground);  
        	calendarLayout.addView(calendarView);
			break;
		}
		case CONTACTS_POS: { // If the user is at the contacts position, inflate the contacts
			layout = inflater.inflate(R.layout.contacts, null);
			contactsList = (ListView)layout.findViewById(R.id.contacts_list);
			contactsList.setAdapter(contactsAdapter);
			contactsList.setOnItemClickListener(this);
			break;
		}
		case ACTIVITYLOG_POS: { // If the user is at the activity log position, inflate the activity log
			layout = inflater.inflate(R.layout.activities, null);
			activitiesList = (ListView) layout.findViewById(R.id.activities_list);
			activitiesList.setAdapter(activityAdapter);
			break;
		}
		default: { // default, pager will never reach this
			layout = inflater.inflate(R.layout.calendar, null);
			break;
		}
		}
		((ViewPager) pager).addView(layout);
		return layout;
	}

	@Override
	public void destroyItem(View pager, int position, Object view) {
		((ViewPager) pager).removeView((View) view);
	}

	@Override
	public boolean isViewFromObject(View view, Object object) {
		return view.equals(object);
	}
	
	@Override
	public int getItemPosition(Object object) {
		return POSITION_NONE;
	}

	@Override
	public void finishUpdate(View view) {
	}

	@Override
	public void restoreState(Parcelable p, ClassLoader c) {
	}

	@Override
	public Parcelable saveState() {
		return null;
	}

	@Override
	public void startUpdate(View view) {
	}

	/**
	 * OnItemClickListener for the ContactsAdapter
	 * If a contact is clicked, display a dialog with the options "delete" or "cancel"
	 */
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) {
		final Contact contact = contacts.get(arg2);
		if(!contact.isMe()) { // If the contact is not the user, then show delete dialog
								// (users cannot delete themselves)
			AlertDialog.Builder alert = new AlertDialog.Builder(context);
			alert.setTitle("Delete?");
			alert.setMessage("Would you like to delete this contact?");
			// If the delete button is clicked, delete the contact
			alert.setPositiveButton("Delete", new DialogInterface.OnClickListener(){
				public void onClick(DialogInterface dialog, int which) {
					db.deleteContact(contact.getID()); // delete contact from database
					String activityText = db.addActivity(contact.getName(), contact.getCalendarName(), 1);
					activities.add(activityText); // add a new activity to the activity log
					contacts.remove(arg2); // delete contact from contacts list
					// Notify all adapters
					activityAdapter.notifyDataSetChanged();
					contactsAdapter.notifyDataSetChanged();
					notifyDataSetChanged();
				}
			});
			alert.setNegativeButton("Cancel", null);
			alert.show();
		}
	}
	
	

}
